package com.itheima.gatewayadmin.filter;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ljh
 * @version 1.0
 * @date 2021/11/28 09:00
 * @description 标题
 * @package com.itheima.gatewayadmin.filter
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    //实现逻辑的业务代码  所有的请求都会经过这个方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取当前请求的路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //2.判断是否需要校验【白名单：登录，注册，获取验证码 等】 如果是白名单 则放行
        //+ filter判断 knif4j的路径 放行

        if(path.endsWith("/admin/admin/login") || path.endsWith("/v2/api-docs")){
            return chain.filter(exchange);
        }

        //3.先从请求头中获取令牌数据
        String token = request.getHeaders().getFirst("token");
        //4 校验 是否合法 如果不是 ，返回错误
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成请求响应 不需要往后走
            return response.setComplete();
        }

        Integer code = AppJwtUtil.verifyToken(token);

        Integer  code1 = 129;
        Integer code2 = 129;
        System.out.println(code1==code2);
        Integer  code3 = 120;
        Integer code4 = 120;
        System.out.println(code3==code4);

        if(code != SystemConstants.JWT_OK){// !=1    说明错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成请求响应 不需要往后走
            return response.setComplete();
        }

        //5. 如果是 则放行。
        return chain.filter(exchange);
    }


    // 定义过滤器执行的优先级  数字越低 优先级越高  --》servlet filter chain
    @Override
    public int getOrder() {
        return 0;
    }
}
